#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
#include <string.h>

#define DEFAULT_PORT 7000
#define DEFAULT_BACKLOG 128

uv_loop_t *loop;
struct sockaddr_in addr;

void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf)
{
    buf->base = (char *)malloc(suggested_size);
    buf->len = suggested_size;
}
void on_read(uv_stream_t *stream,
             ssize_t nread,
             const uv_buf_t *buf)
{
    if (nread > 0)
    {
        for (int i = 0; i < nread; i++)
        {
            printf("%c", buf->base[i]);
        }
        uv_read_stop(stream);
    }
}
void on_write(uv_write_t *req, int status)
{
    printf("write something\n");
}

void on_connect(uv_connect_t *req, int status)
{
    if (status)
    {
        printf(uv_strerror(status), "\n");
    }
    else
    {
        printf("connect success\n");
        uv_read_start(req->handle, alloc_buffer, on_read);
        uv_write_t wr;
        uv_buf_t buf;
        char *str = "hello\n";
        buf = uv_buf_init(str, strlen(str));
        uv_write(&wr, req->handle, &buf, 1, on_write);
    }
}

int main()
{
    loop = uv_default_loop();
    uv_tcp_t dest;
    uv_tcp_init(loop, &dest);
    uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &addr);
    uv_connect_t *connect = (uv_connect_t *)malloc(sizeof(uv_connect_t));
    int r = uv_tcp_connect(connect, &dest, (const sockaddr *)&addr, on_connect);
    if (r)
    {
        printf(uv_strerror(r), "\n");
    }
    else
    {
        uv_run(loop, UV_RUN_DEFAULT);
        uv_close((uv_handle_t *)&dest, nullptr);
    }
    return 0;
}
